package top.jle.spring.basic.sensitive;

import com.alibaba.fastjson2.filter.ValueFilter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
import top.jle.spring.basic.config.WebProperties;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
public class SensitiveValueFilter implements ValueFilter {
    @Resource
    HttpServletRequest request;
    private final WebProperties.SensitiveConfig sensitiveConfig;

    public SensitiveValueFilter(WebProperties.SensitiveConfig sensitiveConfig) {
        this.sensitiveConfig = sensitiveConfig;
    }

    @Override
    public Object apply(Object object, String name, Object value) {
        if (Map.class.isAssignableFrom(object.getClass())|| ObjectUtils.isEmpty(value) || !(value instanceof String)) {
            return value;
        }
        Field field = ReflectionUtils.findField(object.getClass(),name);
        if(field==null){
            return value;
        }
        SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
        if (String.class != field.getType() || ObjectUtils.isEmpty(sensitiveField)) {
            return value;
        }
        String originVal = String.valueOf(value);
        String markFields = request.getParameter(sensitiveConfig.getSwitchOnProperty());
        boolean mark = Boolean.parseBoolean(markFields);
        if(mark){
            //如果 switchOnProperty参数为ture 则所有@SensitiveField字段脱敏
            return sensitiveField.type().mark(originVal);
        }else if(StringUtils.isNotBlank(markFields)){
            List<String> fields = Arrays.asList(markFields.split(","));
            if(fields.contains(name)){
                return sensitiveField.type().mark(originVal);
            }
        }
        return originVal;
    }
}
